package com.lanhe.order.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lanhe.common.constant.Constants;
import com.lanhe.common.constant.HttpStatus;
import com.lanhe.common.core.domain.entity.LhMemberBase;
import com.lanhe.common.exception.ServiceException;
import com.lanhe.common.utils.DateUtils;
import com.lanhe.common.utils.StringUtils;
import com.lanhe.common.utils.kayu.KayuUtil;
import com.lanhe.common.utils.kayu.vo.KayuApplyVO;
import com.lanhe.member.service.*;
import com.lanhe.order.domain.LhOrdersKayu;
import com.lanhe.order.domain.LhOrdersKayuLog;
import com.lanhe.order.domain.LhOrdersPool;
import com.lanhe.order.domain.dto.LhOrdersKayuApplyDto;
import com.lanhe.order.mapper.LhOrdersKayuMapper;
import com.lanhe.order.service.ILhOrdersKayuLogService;
import com.lanhe.order.service.ILhOrdersKayuService;
import com.lanhe.order.service.ILhOrdersPoolService;
import com.lanhe.product.domain.LhKayuProduct;
import com.lanhe.product.service.ILhKayuProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.temporal.WeekFields;
import java.util.*;

/**
 * 卡鱼订单表(LhOrdersKayu)表服务实现类
 *
 * @author zhanggl
 * @since 2023-12-22 18:01:04
 */
@Service
public class LhOrdersKayuServiceImpl extends ServiceImpl<LhOrdersKayuMapper, LhOrdersKayu> implements ILhOrdersKayuService {

	@Autowired
	private LhOrdersKayuMapper ordersKayuMapper;

	@Autowired
	private ILhOrdersKayuLogService ordersKayuLogService;

	@Autowired
	private ILhKayuProductService kayuProductService;

	@Autowired
	private ILhMemberBaseService memberBaseService;


	@Autowired
	private ILhOrdersPoolService ordersPoolService;

	@Autowired
	private ILhStatYearIncomeService yearIncomeService;

	@Autowired
	private ILhStatMonthlyIncomeService monthlyIncomeService;

	@Autowired
	private ILhStatWeeklyIncomeService weeklyIncomeService;

	@Autowired
	private ILhStatDailyIncomeService dailyIncomeService;

	@Autowired
	private KayuUtil kayuUtil;

	private final PlatformTransactionManager transactionManager;

	@Autowired
	public LhOrdersKayuServiceImpl(PlatformTransactionManager transactionManager) {
		this.transactionManager = transactionManager;
	}


	/**
	 * 新增数据（卡鱼进件）
	 *
	 * @param applyDto 实体对象DTO
	 * @return 新增结果
	 */
	@Override
	public Integer insertOrdersKayu(LhOrdersKayuApplyDto applyDto) {

		LhMemberBase user = memberBaseService.getUserByUserKey(applyDto.getUserKey());
		if (ObjectUtil.isNull(user)) {
			throw new ServiceException("查询异常，用户数据不存在", HttpStatus.ERROR);
		}

		// 获取产品详情
		LhKayuProduct lhKayuProduct = kayuProductService.selectKayuProductById(applyDto.getProductId());
		if (ObjectUtil.isNull(lhKayuProduct)) {
			throw new ServiceException("查询异常，数据不存在", HttpStatus.ERROR);
		}

		LhOrdersKayu lhOrdersKayu = selectByIdNoAndProductId(applyDto.getIdNo(), applyDto.getProductId());
		if (ObjectUtil.isNotNull(lhOrdersKayu)) {
			throw new ServiceException("此用户已申请，请勿重复申请", HttpStatus.ERROR);
		}
		try {

			LhOrdersKayu ordersKayu = new LhOrdersKayu();
			// 生成订单号
			String orderNumber = DateUtils.generateOrderCode();
			ordersKayu.setOrderNumber(orderNumber);
			ordersKayu.setProductId(lhKayuProduct.getProductId());
			ordersKayu.setProductName(lhKayuProduct.getProductName());
			ordersKayu.setProductLog(lhKayuProduct.getProductLogo());
			ordersKayu.setMemberId(user.getMemberId());
			ordersKayu.setUsername(applyDto.getUsername());
			ordersKayu.setPhone(applyDto.getPhone());
			ordersKayu.setIdNo(applyDto.getIdNo());
			ordersKayu.setCreateTime(new Date());

			String resource = kayuUtil.merchantApply(
					lhKayuProduct.getKayuId(),
					ordersKayu.getUsername(),
					ordersKayu.getPhone(),
					ordersKayu.getIdNo(),
					ordersKayu.getOrderNumber());
			KayuApplyVO kayuApplyVo = JSONObject.parseObject(resource, KayuApplyVO.class);
			if (!Constants.GeneralIntType.ONE.equals(kayuApplyVo.getStatus())) {
				throw new ServiceException("提交失败->" + kayuApplyVo.getMessage(), HttpStatus.ERROR);
			}
			ordersKayu.setOrderKayuId(kayuApplyVo.getData().getId());
			ordersKayu.setOrderKayuNumber(kayuApplyVo.getData().getOrderId());
			ordersKayu.setUrl(kayuApplyVo.getData().getUrl());
			ordersKayuMapper.insert(ordersKayu);
			return ordersKayu.getOrderId().intValue();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 查询数据，根据身份证号
	 *
	 * @param idNo 身份证号码
	 * @return 新增结果
	 */
	public LhOrdersKayu selectByIdNoAndProductId(String idNo, Long productId) {
		LambdaQueryWrapper<LhOrdersKayu> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(LhOrdersKayu::getIdNo, idNo);
		queryWrapper.eq(LhOrdersKayu::getProductId, productId);
		return ordersKayuMapper.selectOne(queryWrapper);
	}

	/**
	 * 卡鱼进件-回调通知
	 *
	 * @param params 实体对象
	 */
	@Override
	public void settlementNotice(Map<String, String> params) throws Exception {

		Map<String, String> formSign = new HashMap<>();
		String signKayu = "";
		String orderId = "";
		String state = "";
		for (String key : params.keySet()) {
			formSign.put(key, params.get(key));
			if ("sign".equals(key)) {
				signKayu = params.get(key);
			}
			if ("orderId".equals(key)) {
				orderId = params.get(key);
			}
			if ("state".equals(key)) {
				state = params.get(key);
			}
		}

		// 插入回调日志
		LhOrdersKayuLog lhOrdersKayuLog = new LhOrdersKayuLog();
		lhOrdersKayuLog.setOrderId(orderId);
		lhOrdersKayuLog.setState(state);
		lhOrdersKayuLog.setSign(signKayu);
		lhOrdersKayuLog.setFromTxt(JSON.toJSONString(formSign));
		ordersKayuLogService.insertOrdersKayuLog(lhOrdersKayuLog);

		if (StringUtils.isBlank(signKayu) || StringUtils.isBlank(signKayu) || StringUtils.isBlank(signKayu)) {
			updateOrdersKayuLog(lhOrdersKayuLog.getOrderKayuLogId(), Constants.GeneralIntType.TWO, "缺少必要条件");
			throw new ServiceException("缺少必要条件", HttpStatus.ERROR);
		}
		String sign = StringUtils.generateSignatureKayu(formSign, kayuUtil.getMd5Key());
		if (!signKayu.equals(sign)) {
			updateOrdersKayuLog(lhOrdersKayuLog.getOrderKayuLogId(), Constants.GeneralIntType.TWO, "签名验证失败");
			throw new ServiceException("签名验证失败", HttpStatus.ERROR);
		}
		LhOrdersKayu ordersKayu = selectByOrderNumber(orderId);
		if (ObjectUtil.isNull(ordersKayu)) {
			updateOrdersKayuLog(lhOrdersKayuLog.getOrderKayuLogId(), Constants.GeneralIntType.TWO, "订单查询异常");
			throw new ServiceException("订单查询异常", HttpStatus.ERROR);
		}
		if (StringUtils.isNotBlank(ordersKayu.getStatus())) {
			updateOrdersKayuLog(lhOrdersKayuLog.getOrderKayuLogId(), Constants.GeneralIntType.TWO, "订单不允许重复更新");
			throw new ServiceException("订单更新异常", HttpStatus.ERROR);
		}

		// 获取产品详情
		LhKayuProduct lhKayuProduct = kayuProductService.selectKayuProductById(ordersKayu.getProductId());
		if (ObjectUtil.isNull(lhKayuProduct)) {
			updateOrdersKayuLog(lhOrdersKayuLog.getOrderKayuLogId(), Constants.GeneralIntType.TWO, "查询异常，产品数据不存在");
			throw new ServiceException("查询异常，产品数据不存在", HttpStatus.ERROR);
		}

		TransactionStatus transactionStatus = transactionManager.getTransaction(new DefaultTransactionDefinition());
		try {

			// 更新订单
			LhOrdersKayu order = new LhOrdersKayu();
			order.setStatus(state);
			BigDecimal profit = BigDecimal.ZERO;
			switch (state) {
				case Constants.APPLY_KAYU_STATUS_1:
					profit = lhKayuProduct.getRewardAmount();
					break;
				case Constants.APPLY_KAYU_STATUS_2:
					profit = lhKayuProduct.getDemotedAmount();
					break;
				case Constants.APPLY_KAYU_STATUS_3:
					profit = lhKayuProduct.getExtraAmount();
					break;
			}

			order.setProfit(profit);
			order.setOrderId(ordersKayu.getOrderId());
			order.setUpdateTime(new Date());
			ordersKayuMapper.updateById(order);

			LocalDate date = LocalDate.now();
			String year = date.getYear() + "";
			String yearMonth = StringUtils.join(date.getYear(), date.getMonthValue());
			String yearMonthDay = StringUtils.join(date.getYear(), date.getMonthValue(), date.getDayOfMonth());

			// 获取当前日期-周
			WeekFields weekFields = WeekFields.of(Locale.getDefault());
			Integer currentWeek = date.get(weekFields.weekOfWeekBasedYear());


			// 添加主订单
			LhOrdersPool ordersPool = new LhOrdersPool();
			ordersPool.setOrderNumber(ordersKayu.getOrderNumber());
			ordersPool.setMemberId(ordersKayu.getMemberId());
			ordersPool.setOrigin(Constants.ORDERS_ORIGIN_KAYU);
			ordersPool.setOrderId(ordersKayu.getOrderId());
			ordersPool.setRevenueType(Constants.ORDERS_REVENUE_TYPE_0);
			ordersPool.setProductName(lhKayuProduct.getProductName());
			ordersPool.setProductLog(lhKayuProduct.getProductLogo());
			ordersPool.setYear(Integer.valueOf(year));
			ordersPool.setMonthly(Integer.valueOf(yearMonth));
			ordersPool.setWeekly(currentWeek);
			ordersPool.setDaily(Integer.valueOf(yearMonthDay));

			// todo 需要记录区分金额比例分配---后期优化
			ordersPool.setMediaAmount(order.getProfit());
			ordersPool.setAmount(order.getProfit());
			ordersPool.setStatus(Constants.GeneralIntType.ONE.toString());
			ordersPool.setReason(order.getReason());
			ordersPoolService.insertOrdersPool(ordersPool);

			// 更新会员收益
			if (profit.compareTo(BigDecimal.ZERO) > 0){
				memberBaseService.updateMemberBenefits(ordersPool);
			}

			// 更新日志
			updateOrdersKayuLog(lhOrdersKayuLog.getOrderKayuLogId(), Constants.GeneralIntType.ONE, "正常");

			// 提交订单
			transactionManager.commit(transactionStatus);
		} catch (Exception e) {
			transactionManager.rollback(transactionStatus);
			updateOrdersKayuLog(lhOrdersKayuLog.getOrderKayuLogId(), Constants.GeneralIntType.TWO, "处理异常=>" + e.getMessage());
			throw new ServiceException("处理异常=>" + e.getMessage());
		}
	}

	/**
	 * 分页查询所有数据
	 *
	 * @param ordersKayu 实体
	 * @return java.util.List<com.lanhe.order.domain.LhOrdersQingchuang>
	 * @author zhanggl
	 * @date 2023/12/25
	 */
	@Override
	public List<LhOrdersKayu> selectOrdersList(LhOrdersKayu ordersKayu) {
		LambdaQueryWrapper<LhOrdersKayu> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(ObjectUtil.isNotNull(ordersKayu.getMemberId()), LhOrdersKayu::getMemberId, ordersKayu.getMemberId());
		queryWrapper.eq(ObjectUtil.isNotNull(ordersKayu.getStatus()), LhOrdersKayu::getStatus, ordersKayu.getStatus());
		queryWrapper.like(StringUtils.isNotBlank(ordersKayu.getProductName()), LhOrdersKayu::getProductName, ordersKayu.getProductName());
		queryWrapper.orderByDesc(LhOrdersKayu::getOrderId);
		return ordersKayuMapper.selectList(queryWrapper);
	}

	private void updateOrdersKayuLog(Long orderKayuLogId, Integer status, String reason) {
		LhOrdersKayuLog ordersKayuLog = new LhOrdersKayuLog();
		ordersKayuLog.setOrderKayuLogId(orderKayuLogId);
		ordersKayuLog.setStatus(status);
		ordersKayuLog.setReason(reason);
		ordersKayuLogService.updateOrdersKayuLog(ordersKayuLog);
	}


	/**
	 * 根据订单orderNumber 查询订单
	 *
	 * @param orderNumber 订单编号
	 */
	public LhOrdersKayu selectByOrderNumber(String orderNumber) {
		LambdaQueryWrapper<LhOrdersKayu> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(LhOrdersKayu::getOrderNumber, orderNumber);
		return ordersKayuMapper.selectOne(queryWrapper);
	}
}

